package bootstrap

// 初始化自定义验证器

import (
	"go-mp-starter/utils"
	"reflect"
	"strings"

	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
)

var validateFuncs = map[string]validator.Func{
	// 手机号验证器
	"mobile": utils.ValidateMobile,
}

// InitValidator 注册自定义验证器
func InitValidator() {
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {

		// 注册自定义json tag函数
		v.RegisterTagNameFunc(func(field reflect.StructField) string {
			name := strings.SplitN(field.Tag.Get("json"), ",", 2)[0]
			if name == "-" {
				return ""
			}
			return name
		})

		// 注册自定义验证器
		for tag, fn := range validateFuncs {
			_ = v.RegisterValidation(tag, fn)
		}
	}
}
